package it.univaq.disim.mwt.business.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import it.univaq.disim.mwt.business.CorsiService;
import it.univaq.disim.mwt.business.model.Corso;

public class JDBCCorsoService implements CorsiService {
	
	//FUNZIONA
	@Override
	public Corso findCorsoById(Long id) {
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		
		String sql = "select * from corsi where id = ? ";
		Corso corso = null;
		
		try {
			connection = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:XE", "school", "school");
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setLong(1, id);
			preparedStatement.executeQuery();
			resultSet = preparedStatement.getResultSet();
			resultSet.next();
			
			Long ide = resultSet.getLong("id");
			String nome = resultSet.getString("nome");
			
			corso = new Corso(ide, nome);
			
			resultSet.close();
			preparedStatement.close();
			connection.close();
			
			return corso ;

		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		return null;
	}

	//FUNZIONA
	@Override
	public List<Corso> findAllCorsi() {
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		
		List<Corso> listCorsi = new ArrayList<Corso>();
		String sql = "select * from corsi ";
		Corso corso = null;
		
		try {
			connection = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:XE", "school", "school");
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.executeQuery();				
			resultSet=preparedStatement.getResultSet();
		
			while(resultSet.next())
			{
				Long ide = resultSet.getLong("id");
				String nome = resultSet.getString("nome");
				
				corso = new Corso(ide, nome);
				listCorsi.add(corso);
			}
			
			resultSet.close();
			preparedStatement.close();
			connection.close();
			
			return listCorsi;

		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		return null;
	}

}